package com.ruoyi.framework.web.error;

import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.exception.DemoModeException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.result.R;
import net.dreamlu.mica.core.result.SystemCode;
import net.dreamlu.mica.core.utils.$;
import net.dreamlu.mica.redis.ratelimiter.RateLimiterException;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author ruoyi
 */
@Slf4j
@Configuration(proxyBeanMethods = false)
@RequiredArgsConstructor
@RestControllerAdvice
public class GlobalExceptionHandler {
    private final ApplicationEventPublisher publisher;

    /**
     * 通用异常
     */
    @ExceptionHandler(CustomException.class)
    public R businessException(CustomException e) {
        if ($.isNull(e.getCode())) {
            return R.fail(e.getMessage());
        }
        return R.fail(new CustomCode(e.getCode(), e.getMessage()));
    }

    @ExceptionHandler(AccessDeniedException.class)
    public R handleAuthorizationException(AccessDeniedException e) {
        log.error(e.getMessage());
        return R.fail("没有权限，请联系管理员授权");
    }

    @ExceptionHandler(AccountExpiredException.class)
    public R handleAccountExpiredException(AccountExpiredException e) {
        log.error(e.getMessage(), e);
        return R.fail(e.getMessage());
    }

    @ExceptionHandler(UsernameNotFoundException.class)
    public R handleUsernameNotFoundException(UsernameNotFoundException e) {
        log.error(e.getMessage(), e);
        return R.fail(e.getMessage());
    }

    /**
     * 演示模式异常
     */
    @ExceptionHandler(DemoModeException.class)
    public R demoModeException(DemoModeException e) {
        return R.fail("演示模式，不允许操作");
    }

    /**
     * 被限流异常
     */
    @ExceptionHandler(RateLimiterException.class)
    public R<Object> handleError(RateLimiterException e) {
        log.info("请求过于频繁:{}", e.getMessage());
        return R.fail(SystemCode.REQ_REJECT, "请求过于频繁，请稍后再试");
    }
}
